package com.hunter.sign.server.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.hunter.common.base.BaseController;
import com.hunter.common.util.EhCacheUtil;
import com.hunter.sign.common.constant.SignConstant;
import com.hunter.sign.common.constant.SignResult;
import com.hunter.sign.common.constant.SignResultConstant;
import com.hunter.sign.dao.model.SignUser;
import com.hunter.sign.rpc.api.SignUserService;


/**
 * token拦截器
 * Created by hunter on 2017/6/8.
 *
 */
public class TokenInterceptor extends BaseController implements HandlerInterceptor{

	private Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);

	@Autowired
	private SignUserService signUserService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		
		logger.info("check token:::");
		
		String url = request.getRequestURI();
		logger.info("------------------->url:" +url);
		String u[] = url.split("/");
		
		if(u.length==0)
			return true;
		
		url = u[u.length - 1];
		
		if (url.equals("login") || url.equals("register") || url.equals("into")) {
			return true;
		}
		
		String token = request.getHeader("token");
		logger.info("token:::"+token);
		//登录失效处理
		if (EhCacheUtil.get(SignConstant.TOKEN_CACHE, token) == null) {
			logger.error("------------------->url:token已失效。");
			outHttpJson(response, new SignResult(SignResultConstant.INVALID_TOKEN, null));
			return false;
		}
		SignUser SignUser = signUserService.selectByPrimaryKey((Long)EhCacheUtil.get(SignConstant.TOKEN_CACHE, token));
//		SignUser SignUser = signUserService.selectByPrimaryKey(1L);
		request.setAttribute(SignConstant.TOKEN_USER, SignUser);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}
}

